package zd.cornermemory.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Random;

import zd.cornermemory.R;
import zd.cornermemory.bean.CoordinateKeyValue;
import zd.cornermemory.bean.CornerOrEdge;
import zd.cornermemory.bean.Cube;
import zd.cornermemory.bean.CubeColor;
import zd.cornermemory.bean.DisplayBean;
import zd.cornermemory.bean.NumberType;
import zd.cornermemory.bean.SortCode;
import zd.cornermemory.min2phase.Search;
import zd.cornermemory.min2phase.Tools;
import zd.cornermemory.utils.CoordinateUtil;
import zd.cornermemory.utils.SPUtils;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Statistics;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static java.lang.Integer.parseInt;
import static zd.cornermemory.R.string.corner;
import static zd.cornermemory.R.string.edge;

/**
 * Created by zhud on 2019/4/29.
 * 读码
 */

public class ReadCodeFragment extends Fragment{
    private LinearLayout up_corner_0;
    private LinearLayout up_corner_1;
    private LinearLayout up_corner_2;
    private LinearLayout up_corner_3;
    private LinearLayout up_edge_0;
    private LinearLayout up_edge_1;
    private LinearLayout up_edge_2;
    private LinearLayout up_edge_3;
    private LinearLayout up_edge_4;

    private LinearLayout down_corner_0;
    private LinearLayout down_corner_1;
    private LinearLayout down_corner_2;
    private LinearLayout down_corner_3;
    private LinearLayout down_edge_0;
    private LinearLayout down_edge_1;
    private LinearLayout down_edge_2;
    private LinearLayout down_edge_3;
    private LinearLayout down_edge_4;

    private LinearLayout left_corner_0;
    private LinearLayout left_corner_1;
    private LinearLayout left_corner_2;
    private LinearLayout left_corner_3;
    private LinearLayout left_edge_0;
    private LinearLayout left_edge_1;
    private LinearLayout left_edge_2;
    private LinearLayout left_edge_3;
    private LinearLayout left_edge_4;

    private LinearLayout right_corner_0;
    private LinearLayout right_corner_1;
    private LinearLayout right_corner_2;
    private LinearLayout right_corner_3;
    private LinearLayout right_edge_0;
    private LinearLayout right_edge_1;
    private LinearLayout right_edge_2;
    private LinearLayout right_edge_3;
    private LinearLayout right_edge_4;

    private LinearLayout front_corner_0;
    private LinearLayout front_corner_1;
    private LinearLayout front_corner_2;
    private LinearLayout front_corner_3;
    private LinearLayout front_edge_0;
    private LinearLayout front_edge_1;
    private LinearLayout front_edge_2;
    private LinearLayout front_edge_3;
    private LinearLayout front_edge_4;


    private LinearLayout back_corner_0;
    private LinearLayout back_corner_1;
    private LinearLayout back_corner_2;
    private LinearLayout back_corner_3;
    private LinearLayout back_edge_0;
    private LinearLayout back_edge_1;
    private LinearLayout back_edge_2;
    private LinearLayout back_edge_3;
    private LinearLayout back_edge_4;

    private EditText code_edit;
    private Button disrupt_button;
    private Button clear_button;
    private Button random_button;

    private TextView disrupt_type;
    private TextView current_coorniate;
    private TextView corner_buffer;
    private TextView edge_buffer;
    private TextView corner_code;
    private TextView corner_code_fanse;
    private TextView edge_code;
    private TextView edge_code_fanse;
    private TextView coordinate_code;
    private TextView remark;
    private TextView current_corder_sort;
    private TextView current_edge_sort;
    private Toast toast;
    private Toast toastNo;
    private static Random r = new Random();
    private Search cubeSearch = new Search();
    private int read_type;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab2, container, false);
        toast = Toast.makeText(getActivity(),getString(R.string.screamble_faile),Toast.LENGTH_SHORT);
        toastNo = Toast.makeText(getActivity(),getString(R.string.no_exist),Toast.LENGTH_SHORT);
        initViews(view);
        initEvent();
        initCube();
        setCoordinate();
        setBuffer();
        setSort();
        setReadtype();
        registerBroadcast();

        return view;
    }

    private void registerBroadcast() {
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.MODIFY_BUFFER_SUCCESS));
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.MODIFY_COORNIATE_SUCCESS));
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.MODIFY_CODE_SUCCESS));
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.MODIFY_SORT_SUCCESS));
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.MODIFY_READ_SUCCESS));
        getActivity().registerReceiver(broadcastReceiver,new IntentFilter(SpKey.CJ_DNF));
    }

    private void initCube() {
        Cube cube = new Cube();
        cube.init();
        List<DisplayBean> displayBeanList =  cube.getCubeColorStatusData();
        show(displayBeanList);
    }

    private void show(List<DisplayBean> displayBeanList){
        for (DisplayBean displayBean:displayBeanList) {
            switch (displayBean.getCubeDirection()){
                case UP:
                    up_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    up_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    up_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    up_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    up_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    up_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    up_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    up_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    up_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case DOWN:
                    down_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    down_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    down_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    down_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    down_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    down_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    down_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    down_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    down_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case LEFT:
                    left_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    left_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    left_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    left_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    left_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    left_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    left_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    left_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    left_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case RIGHT:
                    right_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    right_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    right_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    right_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    right_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    right_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    right_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    right_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    right_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case FRONT:
                    front_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    front_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    front_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    front_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    front_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    front_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    front_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    front_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    front_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case BACK:
                    back_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    back_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    back_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    back_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    back_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    back_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    back_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    back_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    back_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));
                    break;
            }
        }
    }

    private Drawable getDisplayColor(CubeColor colorEnum){
        Drawable color = null;
        switch (colorEnum) {
            case YELLOW:
                color = getResources().getDrawable(R.drawable.color_yellow_bg);
                break;
            case WIHTE:
                color = getResources().getDrawable(R.drawable.color_white_bg);
                break;
            case BLUE:
                color = getResources().getDrawable(R.drawable.color_blue_bg);
                break;
            case GREEN:
                color = getResources().getDrawable(R.drawable.color_green_bg);
                break;
            case RED:
                color = getResources().getDrawable(R.drawable.color_red_bg);
                break;
            case ORANGE:
                color = getResources().getDrawable(R.drawable.color_orange_bg);
                break;
        }

        return color;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case SpKey.MODIFY_BUFFER_SUCCESS:
                    setBuffer();
                    setSort();
                    break;
                case SpKey.MODIFY_COORNIATE_SUCCESS:
                    setCoordinate();
                    initCube();
                    break;
                case SpKey.MODIFY_CODE_SUCCESS:
                    setSort();
                    break;
                case SpKey.MODIFY_SORT_SUCCESS:
                    setSort();
                    break;
                case SpKey.MODIFY_READ_SUCCESS:
                    setReadtype();
                    break;
                case SpKey.CJ_DNF:
                    String currentCode = intent.getExtras().getString("currentCode", "");
                    if (code_edit != null) {
                        code_edit.setText(currentCode);
                        disrupt();
                    }
                    break;
            }
        }
    };

    private void setReadtype() {
        read_type = SPUtils.getInstance().getInt(SpKey.READ_TYPE, 0);
        if (read_type == 0) {
            disrupt_type.setVisibility(View.GONE);
        }else {
            disrupt_type.setVisibility(View.VISIBLE);
        }
    }

    private void initViews(View view) {
        up_corner_0 = view.findViewById(R.id.up_corner_0);
        up_corner_1 = view.findViewById(R.id.up_corner_1);
        up_corner_2 = view.findViewById(R.id.up_corner_2);
        up_corner_3 = view.findViewById(R.id.up_corner_3);
        up_edge_0 = view.findViewById(R.id.up_edge_0);
        up_edge_1 = view.findViewById(R.id.up_edge_1);
        up_edge_2 = view.findViewById(R.id.up_edge_2);
        up_edge_3 = view.findViewById(R.id.up_edge_3);
        up_edge_4 = view.findViewById(R.id.up_edge_4);

        down_corner_0 = view.findViewById(R.id.down_corner_0);
        down_corner_1 = view.findViewById(R.id.down_corner_1);
        down_corner_2 = view.findViewById(R.id.down_corner_2);
        down_corner_3 = view.findViewById(R.id.down_corner_3);
        down_edge_0 = view.findViewById(R.id.down_edge_0);
        down_edge_1 = view.findViewById(R.id.down_edge_1);
        down_edge_2 = view.findViewById(R.id.down_edge_2);
        down_edge_3 = view.findViewById(R.id.down_edge_3);
        down_edge_4 = view.findViewById(R.id.down_edge_4);


        left_corner_0 = view.findViewById(R.id.left_corner_0);
        left_corner_1 = view.findViewById(R.id.left_corner_1);
        left_corner_2 = view.findViewById(R.id.left_corner_2);
        left_corner_3 = view.findViewById(R.id.left_corner_3);
        left_edge_0 = view.findViewById(R.id.left_edge_0);
        left_edge_1 = view.findViewById(R.id.left_edge_1);
        left_edge_2 = view.findViewById(R.id.left_edge_2);
        left_edge_3 = view.findViewById(R.id.left_edge_3);
        left_edge_4 = view.findViewById(R.id.left_edge_4);


        right_corner_0 = view.findViewById(R.id.right_corner_0);
        right_corner_1 = view.findViewById(R.id.right_corner_1);
        right_corner_2 = view.findViewById(R.id.right_corner_2);
        right_corner_3 = view.findViewById(R.id.right_corner_3);
        right_edge_0 = view.findViewById(R.id.right_edge_0);
        right_edge_1 = view.findViewById(R.id.right_edge_1);
        right_edge_2 = view.findViewById(R.id.right_edge_2);
        right_edge_3 = view.findViewById(R.id.right_edge_3);
        right_edge_4 = view.findViewById(R.id.right_edge_4);

        front_corner_0 = view.findViewById(R.id.front_corner_0);
        front_corner_1 = view.findViewById(R.id.front_corner_1);
        front_corner_2 = view.findViewById(R.id.front_corner_2);
        front_corner_3 = view.findViewById(R.id.front_corner_3);
        front_edge_0 = view.findViewById(R.id.front_edge_0);
        front_edge_1 = view.findViewById(R.id.front_edge_1);
        front_edge_2 = view.findViewById(R.id.front_edge_2);
        front_edge_3 = view.findViewById(R.id.front_edge_3);
        front_edge_4 = view.findViewById(R.id.front_edge_4);

        back_corner_0 = view.findViewById(R.id.back_corner_0);
        back_corner_1 = view.findViewById(R.id.back_corner_1);
        back_corner_2 = view.findViewById(R.id.back_corner_2);
        back_corner_3 = view.findViewById(R.id.back_corner_3);
        back_edge_0 = view.findViewById(R.id.back_edge_0);
        back_edge_1 = view.findViewById(R.id.back_edge_1);
        back_edge_2 = view.findViewById(R.id.back_edge_2);
        back_edge_3 = view.findViewById(R.id.back_edge_3);
        back_edge_4 = view.findViewById(R.id.back_edge_4);

        code_edit = view.findViewById(R.id.code_edit);
        disrupt_button = view.findViewById(R.id.disrupt_button);
        clear_button = view.findViewById(R.id.clear_button);
        random_button = view.findViewById(R.id.random_button);

        current_coorniate = view.findViewById(R.id.current_coorniate);
        corner_buffer = view.findViewById(R.id.corner_buffer);
        edge_buffer = view.findViewById(R.id.edge_buffer);
        corner_code = view.findViewById(R.id.corner_code);
        corner_code_fanse = view.findViewById(R.id.corner_code_fanse);
        edge_code = view.findViewById(R.id.edge_code);
        edge_code_fanse = view.findViewById(R.id.edge_code_fanse);
        coordinate_code = view.findViewById(R.id.coordinate_code);
        remark = view.findViewById(R.id.remark);
        current_corder_sort = view.findViewById(R.id.current_corder_sort);
        current_edge_sort = view.findViewById(R.id.current_edge_sort);
        disrupt_type = view.findViewById(R.id.disrupt_type);
    }

    private void setSort(){
        boolean iskeepHue = SPUtils.getInstance().getBoolean(SpKey.KEEP_HUE);
        boolean iskeepHueEdge = SPUtils.getInstance().getBoolean(SpKey.KEEP_HUE_EDGE);

        SpannableStringBuilder ssb = new SpannableStringBuilder();

        SpannableString ss = new SpannableString(getString(R.string.blue_jie));
        ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#0000FF"));
        ss.setSpan(span,0,4, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ssb.append(ss);

        SpannableString ss2 = new SpannableString(getString(R.string.green_hw));
        ForegroundColorSpan span2 = new ForegroundColorSpan(getResources().getColor(R.color.green_text));
        ss2.setSpan(span2,0,4, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ssb.append(ss2);

        if(iskeepHue&&iskeepHueEdge){
            ssb.append(getString(R.string.is_bc));
        }else if(!iskeepHue&&!iskeepHueEdge){
            ssb.append(getString(R.string.no_bc));
        }else{
            if (iskeepHue) {
                ssb.append(getString(R.string.corner_bc));
            }else {
                ssb.append(getString(R.string.corner_no_bc));
            }

            if (iskeepHueEdge) {
                ssb.append(getString(R.string.edge_bc));
            }else {
                ssb.append(getString(R.string.edge_no_bc));
            }

        }
        remark.setText(ssb);
        String cornerSortStr = getString(corner);
        String edgeSortStr = getString(edge);
        List<SortCode>[] sorts = CoordinateUtil.getSortCode(true);
        for(SortCode sc:sorts[0]){
            cornerSortStr+=sc.getDisplay()+" ";
        }
        for(SortCode sc:sorts[1]){
            edgeSortStr+=sc.getDisplay()+" ";
        }
        current_corder_sort.setText(cornerSortStr);
        current_edge_sort.setText(edgeSortStr);
    }

    private void setBuffer() {
        String cornerBufferStr = SPUtils.getInstance().getString(SpKey.CORNER_BUFFER);
        String[] corner = getResources().getStringArray(R.array.corner_buffer);
        if(TextUtils.isEmpty(cornerBufferStr)){
            corner_buffer.setText(getString(R.string.corner_buffer_2)+corner[1]);
        }else{
            corner_buffer.setText(getString(R.string.corner_buffer_2)+corner[Integer.parseInt(cornerBufferStr)]);
        }

        String edgeBufferStr = SPUtils.getInstance().getString(SpKey.EDGE_BUFFER);
        String[] edge = getResources().getStringArray(R.array.edge_buffer);

        if (TextUtils.isEmpty(edgeBufferStr)) {
            edge_buffer.setText(getString(R.string.edge_buffer_2)+edge[2]);
        }else {
            edge_buffer.setText(getString(R.string.edge_buffer_2)+edge[Integer.parseInt(edgeBufferStr)]);
        }
    }

    private void setCoordinate() {
        String coordinateStr = SPUtils.getInstance().getString(SpKey.COORDINATE);
        String[] s = getResources().getStringArray(R.array.coordinate);
        if(TextUtils.isEmpty(coordinateStr)){
            current_coorniate.setText(getString(R.string.fyzb)+s[2]);
        }else{
           List<String> flags =  CoordinateUtil.getcoordinateFlag();
            for(int i = 0;i<flags.size();i++) {
                if (TextUtils.equals(coordinateStr, flags.get(i))) {
                    current_coorniate.setText(getString(R.string.dqzb)+s[i]);
                    break;
                }
            }
        }
    }

    private void initEvent() {

        disrupt_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                disrupt();
            }
        });

        random_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                read_type = SPUtils.getInstance().getInt(SpKey.READ_TYPE, 0);
                if (read_type == 0) {
                    disrupt_type.setVisibility(View.GONE);
                    code_edit.setText(getString(R.string.dl_));
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            String c = Tools.randomCube();
                            String scr = cubeSearch.solution(c, true, r);
                            code_edit.setText(Statistics.getFormatCodes(scr));
                            code_edit.setSelection(Statistics.getFormatCodes(scr).length());
                            disrupt();
                        }
                    });
                }else {
                    disrupt_type.setVisibility(View.VISIBLE);
                    initDisrupt();
                }



            }
        });
        clear_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSoftInput();
                code_edit.setText("");
                Cube cube = new Cube();
                cube.init();
                List<DisplayBean> displayBeanList =  cube.getCubeColorStatusData();
                show(displayBeanList);
                coordinate_code.setText(getString(R.string.zbtz));
                corner_code.setText(getString(R.string.corner_code_));
                corner_code_fanse.setText(getString(R.string.corner_fs_));
                edge_code.setText(getString(R.string.edge_code_));
                edge_code_fanse.setText(getString(R.string.edge_fs_));
            }
        });
    }

    private void hideSoftInput() {
        try{
            InputMethodManager mInputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
            assert mInputMethodManager != null;
            mInputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

        }catch (Exception e){

        }
    }
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 11:
                    toastNo.show();
                    break;
                case 22:
                    String disrupt = (String) msg.obj;
                    code_edit.setText(Statistics.getFormatCodes(disrupt));
                    disrupt();
                    break;
                case 33:
                    String result = (String) msg.obj;
                    code_edit.setText(Statistics.getFormatCodes(result));
                    disrupt();
                    break;
            }
        }
    };
    private void disrupt() {
        hideSoftInput();

        String code = code_edit.getText().toString();
        if(isCorrect(code)){
            Cube cube = new Cube();
            cube.init();
            cube.disrupt(code);
            List<DisplayBean> displayBeanList =  cube.getCubeColorStatusData();
            show(displayBeanList);

            String coordinateStr = cube.handlCoordinate();
            coordinate_code.setText(getString(R.string.zbtz)+coordinateStr);
            SpannableStringBuilder[] cornerSsb = cube.readCorner();
            SpannableStringBuilder codeStr = cornerSsb[0];
            SpannableStringBuilder codeFStr = cornerSsb[1];
            corner_code.setText(codeStr);
            corner_code_fanse.setText(codeFStr);

            SpannableStringBuilder[] edgeSsb = cube.readEdge();
            SpannableStringBuilder codeEdgeStr = edgeSsb[0];
            SpannableStringBuilder codeFEdgeStr = edgeSsb[1];

            edge_code.setText(codeEdgeStr);
            edge_code_fanse.setText(codeFEdgeStr);

            return;
        }

        toast.show();
    }

    private boolean isCorrect(String code) {
        String regex = "[RUDLFBEMSxyz'w2\\s]+";
        return code.matches(regex);
    }


    private int dlms_type;
    private String cornerCodeLength;
    private String cornerFanseCount;
    private String cornerXunhuanCount;
    private int cornerIshoming;

    private String edgeCodeLength;
    private String edgeFanseCount;
    private String edgeXunhuanCount;
    private int edgeIshoming;
    private int is_parity_all;
    private int is_dl_zb_all;

    /**
     * 反推部分
     */
    private String cornerCode;
    private String cornerFanse;
    private String edgeCode;
    private String edgeFanse;
    private boolean is23;

    private void initDisrupt(){
        dlms_type = SPUtils.getInstance().getInt(SpKey.DL_MS,0);
        cornerCodeLength = SPUtils.getInstance().getString(SpKey.CORNER_CODE_LENGTH,"");
        cornerFanseCount = SPUtils.getInstance().getString(SpKey.CORNER_FANSE_COUNT,"");
        cornerXunhuanCount =SPUtils.getInstance().getString(SpKey.CORNER_XUNHUAN_COUNT,"");
        cornerIshoming = SPUtils.getInstance().getInt(SpKey.CORNER_IS_HOMING, 0);

        edgeCodeLength = SPUtils.getInstance().getString(SpKey.EDGE_CODE_LENGTH,"");
        edgeFanseCount = SPUtils.getInstance().getString(SpKey.EDGE_FANSE_COUNT,"");
        edgeXunhuanCount = SPUtils.getInstance().getString(SpKey.EDGE_XUNHUAN_COUNT,"");
        edgeIshoming = SPUtils.getInstance().getInt(SpKey.EDGE_IS_HOMING, 0);

        is_parity_all = SPUtils.getInstance().getInt(SpKey.IS_PARITY);
        String isDlzb = SPUtils.getInstance().getString(SpKey.IS_DL_ZB,"0");
        is_dl_zb_all = Integer.parseInt(isDlzb);


        cornerCode = SPUtils.getInstance().getString(SpKey.CORNER_CODE,"");
        cornerFanse = SPUtils.getInstance().getString(SpKey.CORNER_FANSE,"");
        edgeCode = SPUtils.getInstance().getString(SpKey.EDGE_CODE,"");
        edgeFanse = SPUtils.getInstance().getString(SpKey.EDGE_FANSE,"");

        if (dlms_type == 0) {
            Cube cube = new Cube();
            cube.init();

            int[][] cornerRanges = getRanges(CornerOrEdge.CORNER);
            int[][] edgeRanges = getRanges(CornerOrEdge.EDGE);
            boolean isExist = cube.cubeRandomStatus(cornerRanges,edgeRanges,cornerIshoming,edgeIshoming,is_parity_all);
            if (isExist) {
                toScramble(cube);
            }else {
                code_edit.setText("");
                toastNo.show();
                return;
            }
        }else if(dlms_type==1){
            randomCodeType();
        }

    }


    /**
     *
     * @param cornerOrEdge 角或棱
     * @return 二维数组 分别表示 编码长度、翻色数量、小循环数量的取值范围
     */
    private int[][] getRanges(CornerOrEdge cornerOrEdge){
        int[] codeLengthRange = getRange(cornerOrEdge, 0);
        int[] fanseLengthRange = getRange(cornerOrEdge, 1);
        int[] xunhuanLengthRange = getRange(cornerOrEdge, 2);

        int[][] range = {codeLengthRange,fanseLengthRange,xunhuanLengthRange};
        return range;
    }

    /**
     *
     * @param cornerOrEdge 角或棱
     * @param position 0 编码长度 1 翻色数量 2 小循环数
     * @return
     */
    private int[] getRange(CornerOrEdge cornerOrEdge,int position){
        int[] range = {};
        switch (cornerOrEdge) {
            case CORNER:
                if (position == 0) {
                    range = getRangeType(cornerCodeLength);
                } else if (position == 1) {
                    range = getRangeType(cornerFanseCount);
                }else {
                    range = getRangeType(cornerXunhuanCount);
                }
                break;
            case EDGE:
                if (position == 0) {
                    range = getRangeType(edgeCodeLength);
                } else if (position == 1) {
                    range = getRangeType(edgeFanseCount);
                }else {
                    range = getRangeType(edgeXunhuanCount);
                }
                break;
        }

        return range;
    }


    private int[] getRangeType(String counts){
        NumberType numberType = getNumberType(counts);
        int[] rangeType = {};
        switch (numberType) {
            case BETWEEN:
                String[] s = counts.split("-");
                int start = Integer.parseInt(s[0]);
                int end = Integer.parseInt(s[1]);
                rangeType = new int[]{start,end};
                break;
            case PLUS:
                String[] plus = counts.split("\\+");
                int startPlus = Integer.parseInt(plus[0]);
                rangeType = new int[]{startPlus,20};
                break;
            case MINUS:
                String[] minus = counts.split("\\-");
                int endMinus = Integer.parseInt(minus[0]);
                rangeType = new int[]{0,endMinus};
                break;
            case NUMBER:
                int count = parseInt(counts);
                rangeType = new int[]{count,count};
                break;
            case NONE:
                rangeType = new int[]{0,20};//不填写则给个最大范围
                break;
        }
        return rangeType;
    }


    private void randomCodeType(){

        if (cornerCode.length() % 2 != edgeCode.length() % 2) {
            code_edit.setText("");
            toastNo.show();
            return;
        }
        if (cornerFanse.length() > 14) {
            code_edit.setText("");
            toastNo.show();
            return;
        }
        if (edgeFanse.length() > 22) {
            code_edit.setText("");
            toastNo.show();
            return;
        }

        if (cornerFanse.length() % 2 != 0 || edgeFanse.length() % 2 != 0) {
            code_edit.setText("");
            toastNo.show();
            return;
        }

        if (cornerCode.length() == 0 && cornerFanse.length() == 0 && edgeCode.length() == 0 && edgeFanse.length() == 0) {
            code_edit.setText("");
            return;
        }


        if (cornerFanse.length() >= 10 && edgeFanse.length() > 10) {
            is23 = true;
        }else {
            is23 = false;
        }

        Cube cube = new Cube();
        cube.init();
        String result = cube.codeType(cornerCode.toUpperCase(), cornerFanse.toUpperCase(), edgeCode.toUpperCase(), edgeFanse.toUpperCase());
        if (result != null) {
            code_edit.setText("");
            toastNo.show();
            return;
        }
        toScramble(cube);
    }




    private void toScramble(final Cube cube) {
        code_edit.setText(getString(R.string.generate_));
        new Thread(new Runnable() {
            @Override
            public void run() {
                scramble(cube);
            }
        }).start();
    }

    private void scramble(Cube cube) {
        String phaseStr = cube.get2phaseStr();
        int step = 21;
        if (is23) {
            step = 23;
        }
        String result = new Search().solution(phaseStr, step, 100000000, 0, Search.INVERSE_SOLUTION);

        if (result.contains("Error")) {
            mHandler.sendEmptyMessage(11);
            return;
        }

        if (is_dl_zb_all == 0) {//打乱坐标任意
            Random random = new Random();
            int r = random.nextInt(24);
            if (r != 1) {
                dlzb(cube, step);
            }else {
                noDlzb(result);
            }
        } else if (is_dl_zb_all == 1) {//打乱坐标
            dlzb(cube, step);
        }else {//不打乱坐标
            noDlzb(result);
        }

    }

    private void noDlzb(String result) {
        Message message = Message.obtain();
        message.what = 33;
        message.obj = result;
        mHandler.sendMessage(message);
    }

    private void dlzb(Cube cube, int step) {
        CoordinateKeyValue keyValue = CoordinateUtil.coordinateKeyValues.get(new Random().nextInt(CoordinateUtil.coordinateKeyValues.size()));
        cube.disrupt(keyValue.getDisrupt());
        String phaseStr2 = cube.get2phaseStr();
        String result2 = new Search().solution(phaseStr2, step, 100000000, 0, Search.INVERSE_SOLUTION);
        String disrupt = result2+keyValue.getDisplay();
        Message message = Message.obtain();
        message.what = 22;
        message.obj = disrupt;
        mHandler.sendMessage(message);
    }

    private NumberType getNumberType(String code) {
        String between = "(\\d{1,2})(\\-)(\\d{1,2})";
        String plus = "(\\d{1,2})(\\+)";
        String minus = "(\\d{1,2})(\\-)";
        String number = "\\d{1,2}";
        boolean isBetween = code.matches(between);
        boolean isPlus = code.matches(plus);
        boolean isMinus = code.matches(minus);
        boolean isNumber = code.matches(number);
        if (isBetween) {
            return NumberType.BETWEEN;
        } else if (isPlus) {
            return NumberType.PLUS;
        }else if (isMinus) {
            return NumberType.MINUS;
        }else if (isNumber) {
            return NumberType.NUMBER;
        }else {
            return NumberType.NONE;
        }
    }


}
